import requests
import time
from typing import Dict, Any, Optional
from config import EASYSCHOLAR_API_KEY, EASYSCHOLAR_BASE_URL, EASYSCHOLAR_API_ENDPOINT, REQUEST_TIMEOUT, REQUEST_DELAY

class EasyScholarAPI:
    """EasyScholar API客户端"""
    
    def __init__(self, api_key: str = None):
        """
        初始化API客户端
        
        Args:
            api_key: API密钥，如果不提供则使用配置文件中的密钥
        """
        self.api_key = api_key or EASYSCHOLAR_API_KEY
        self.base_url = EASYSCHOLAR_BASE_URL
        self.api_endpoint = EASYSCHOLAR_API_ENDPOINT
        self.session = requests.Session()
        
        # 设置请求头
        self.session.headers.update({
            'Content-Type': 'application/json'
        })
    
    def search_journal_by_issn(self, issn: str) -> Optional[Dict[str, Any]]:
        """
        通过ISSN搜索期刊信息（注意：当前API不支持ISSN查询，将返回None）
        
        Args:
            issn: 期刊ISSN号
            
        Returns:
            期刊信息字典，如果未找到则返回None
        """
        # 当前API接口不支持ISSN查询，静默返回None
        return None
    
    def search_journal_by_title(self, title: str) -> Optional[Dict[str, Any]]:
        """
        通过期刊名称搜索期刊信息
        
        Args:
            title: 期刊名称
            
        Returns:
            期刊信息字典，如果未找到则返回None
        """
        if not title:
            return None
            
        if not self.api_key:
            print("错误: 未提供API密钥 (secretKey)")
            return None
            
        try:
            # 构建请求URL和参数
            url = f"{self.base_url}{self.api_endpoint}"
            params = {
                'secretKey': self.api_key,
                'publicationName': title
            }
            
            response = self.session.get(url, params=params, timeout=REQUEST_TIMEOUT)
            response.raise_for_status()
            
            data = response.json()
            
            # 检查API响应
            if data.get('code') == 200:
                data_content = data.get('data', {})
                if data_content is None:
                    data_content = {}
                return self._extract_quartile_info(data_content, title)
            else:
                print(f"API返回错误 (Title: {title}): {data.get('msg', '未知错误')} (错误代码: {data.get('code')})")
                return None
            
        except requests.exceptions.RequestException as e:
            print(f"查询期刊信息时出错 (Title: {title}): {e}")
            return None
        except Exception as e:
            print(f"处理期刊信息时出错 (Title: {title}): {e}")
            return None
    
    def _extract_quartile_info(self, journal_info: Dict[str, Any], title: str) -> Dict[str, Any]:
        """
        从期刊信息中提取分区信息
        
        Args:
            journal_info: 期刊信息字典
            title: 期刊名称
            
        Returns:
            包含分区信息的字典
        """
        quartile_info = {
            'jcr_quartile': None,
            'cas_quartile': None,
            'journal_name': title,
            'issn': ''
        }
        
        # 检查journal_info是否为空或None
        if not journal_info:
            return quartile_info
        
        # 提取官方排名信息
        official_rank = journal_info.get('officialRank', {})
        if official_rank:
            all_ranks = official_rank.get('all', {})
            if all_ranks and all_ranks is not None:  # 确保all_ranks不是None且不为空
                # 从新的排名系统中提取分区信息
                # sci字段可能对应JCR分区
                sci_rank = all_ranks.get('sci', '')
                if sci_rank:
                    # 将sci排名映射到JCR分区
                    if sci_rank == 'Q1':
                        quartile_info['jcr_quartile'] = 'Q1'
                    elif sci_rank == 'Q2':
                        quartile_info['jcr_quartile'] = 'Q2'
                    elif sci_rank == 'Q3':
                        quartile_info['jcr_quartile'] = 'Q3'
                    elif sci_rank == 'Q4':
                        quartile_info['jcr_quartile'] = 'Q4'
                
                # 尝试从其他字段提取中科院分区信息
                # 这里需要根据实际的映射关系来调整
                # 暂时使用sciBase或sciUp字段作为中科院分区的参考
                sci_base = all_ranks.get('sciBase', '')
                if sci_base:
                    # 根据sciBase的值映射到中科院分区
                    if '1区' in sci_base:
                        quartile_info['cas_quartile'] = 'Q1'
                    elif '2区' in sci_base:
                        quartile_info['cas_quartile'] = 'Q2'
                    elif '3区' in sci_base:
                        quartile_info['cas_quartile'] = 'Q3'
                    elif '4区' in sci_base:
                        quartile_info['cas_quartile'] = 'Q4'
        
        # 提取自定义排名信息（如果有的话）
        custom_rank = journal_info.get('customRank', {})
        if custom_rank:
            rank_info = custom_rank.get('rankInfo', [])
            if rank_info and rank_info is not None:  # 确保rank_info不是None且不为空
                # 可以在这里处理自定义排名信息
                pass
        
        return quartile_info
    
    def get_journal_info(self, journal_info: Dict[str, str]) -> Optional[Dict[str, Any]]:
        """
        获取期刊信息，优先使用期刊名称（当前API只支持期刊名称查询）
        
        Args:
            journal_info: 包含期刊信息的字典
            
        Returns:
            期刊分区信息字典
        """
        # 添加请求延迟
        time.sleep(REQUEST_DELAY)
        
        # 优先使用期刊名称查询
        if journal_info.get('title'):
            result = self.search_journal_by_title(journal_info['title'])
            if result:
                return result
        
        # 如果期刊名称查询失败，尝试使用ISSN（但会失败）
        if journal_info.get('issn'):
            result = self.search_journal_by_issn(journal_info['issn'])
            if result:
                return result
        
        return None